<template>
  <div class="role-container">
    <!-- 背景装饰元素 -->
    <div class="decoration-circle decoration-circle-1"></div>
    <div class="decoration-circle decoration-circle-2"></div>
    <div class="decoration-circle decoration-circle-3"></div>

    <!-- 搜索区域 -->
    <transition name="fade" appear>
      <el-card class="search-card" shadow="hover">
        <el-form :inline="true" class="form">
          <el-form-item label="角色搜索:">
            <el-input
              placeholder="请输入搜索角色关键字"
              v-model="keyword"
              clearable
              prefix-icon="Search"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              size="default"
              :disabled="!keyword"
              @click="search"
              icon="Search"
            >
              搜索
            </el-button>
            <el-button
              type="info"
              size="default"
              @click="reset"
              icon="RefreshRight"
            >
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </transition>

    <!-- 表格区域 -->
    <transition name="slide-fade" appear>
      <el-card class="table-card" shadow="hover">
        <div class="button-group">
          <el-button type="primary" size="default" icon="Plus" @click="addRole">
            添加角色
          </el-button>
        </div>

        <el-table
          border
          style="margin: 8px 0"
          :data="allRole"
          stripe
          highlight-current-row
          class="role-table"
        >
          <el-table-column
            type="index"
            align="center"
            label="#"
            width="60"
          ></el-table-column>
          <el-table-column
            label="ID"
            align="center"
            prop="id"
            width="80"
            sortable
          ></el-table-column>
          <el-table-column
            label="角色名称"
            align="center"
            prop="name"
            show-overflow-tooltip
          >
            <template #default="{ row }">
              <div class="role-name-cell">
                <el-icon><UserFilled /></el-icon>
                <span>{{ row.name }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="描述"
            align="center"
            show-overflow-tooltip
            prop="description"
          >
            <template #default="{ row }">
              <el-tooltip
                :content="row.description"
                placement="top"
                :show-after="500"
              >
                <div class="description-cell">{{ row.description }}</div>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column
            label="角色代码"
            align="center"
            show-overflow-tooltip
            prop="code"
          >
            <template #default="{ row }">
              <el-tag size="small" effect="plain">{{ row.code }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="创建时间"
            align="center"
            show-overflow-tooltip
            prop="createTime"
            width="180"
          >
            <template #default="{ row }">
              <div class="time-cell">
                <el-icon><Calendar /></el-icon>
                <span>{{ formatTime(row.createTime) }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="更新时间"
            align="center"
            show-overflow-tooltip
            prop="updateTime"
            width="180"
          >
            <template #default="{ row }">
              <div class="time-cell">
                <el-icon><Timer /></el-icon>
                <span>{{ formatTime(row.updateTime) }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280px" align="center">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-tooltip content="分配权限" placement="top">
                  <el-button
                    type="primary"
                    size="small"
                    icon="SetUp"
                    @click="setPermission(row)"
                  >
                    分配权限
                  </el-button>
                </el-tooltip>
                <el-tooltip content="编辑角色" placement="top">
                  <el-button
                    type="warning"
                    size="small"
                    icon="Edit"
                    @click="updateRole(row)"
                  >
                    编辑
                  </el-button>
                </el-tooltip>
                <el-popconfirm
                  :title="`确定要删除角色 '${row.name}' 吗?`"
                  width="260px"
                  @confirm="removeRole(row.id)"
                  icon="WarningFilled"
                  icon-color="#F56C6C"
                >
                  <template #reference>
                    <el-tooltip content="删除角色" placement="top">
                      <el-button type="danger" size="small" icon="Delete">
                        删除
                      </el-button>
                    </el-tooltip>
                  </template>
                </el-popconfirm>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          v-model:current-page="pageNo"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 40]"
          :background="true"
          layout="prev, pager, next, jumper,->,sizes,total"
          :total="total"
          @current-change="getHasRole"
          @size-change="sizeChange"
          class="pagination"
        />
      </el-card>
    </transition>

    <!-- 添加角色与更新已有角色的结构:对话框 -->
    <el-dialog
      v-model="dialogVisite"
      draggable
      :title="RoleParams.id ? '更新角色' : '添加角色'"
      width="500px"
      destroy-on-close
    >
      <el-form
        :model="RoleParams"
        :rules="rules"
        ref="form"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input
            placeholder="请输入角色名称"
            v-model="RoleParams.name"
            prefix-icon="User"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input
            placeholder="请输入角色描述"
            v-model="RoleParams.description"
            prefix-icon="Document"
            type="textarea"
            :rows="3"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色代码" prop="code">
          <el-input
            placeholder="请输入角色代码"
            v-model="RoleParams.code"
            prefix-icon="Key"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisite = false" icon="Close">取消</el-button>
          <el-button type="primary" @click="save" icon="Check">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 抽屉组件:分配角色的菜单权限与按钮的权限 -->
    <el-drawer
      v-model="drawer"
      title="分配菜单与按钮的权限"
      size="400px"
      destroy-on-close
    >
      <template #header>
        <div class="drawer-header">
          <el-icon><SetUp /></el-icon>
          <h4>分配菜单与按钮的权限</h4>
        </div>
      </template>
      <template #default>
        <!-- 权限多选 -->
        <div class="permission-container">
          <div class="current-role-info">
            <el-icon><UserFilled /></el-icon>
            <span>当前角色: {{ RoleParams.name }}</span>
          </div>
          <el-divider content-position="center">权限列表</el-divider>
          <el-checkbox-group
            v-model="selectArr"
            class="permission-checkbox-group"
          >
            <el-checkbox
              v-for="perm in menuArr"
              :key="perm.id"
              :label="perm.id"
              class="permission-checkbox"
            >
              <div class="permission-item">
                <el-icon><Menu /></el-icon>
                <span class="permission-name">{{ perm.name }}</span>
                <el-tag size="small" effect="plain" class="permission-desc">
                  {{ perm.description }}
                </el-tag>
              </div>
            </el-checkbox>
          </el-checkbox-group>
        </div>
      </template>
      <template #footer>
        <div class="drawer-footer">
          <el-button @click="drawer = false" icon="Close">取消</el-button>
          <el-button type="primary" @click="handler" icon="Check">
            确定
          </el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
//引入骨架的仓库
import useLayOutSettingStore from '@/store/modules/setting'
import {
  reqAllRoleList,
  reqAddOrUpdateRole,
  reqRemoveRole,
  reqAllMenuList,
  reqSetPermission,
  RoleData,
  RoleResponseData,
  MenuResponseData,
  Permission,
} from '@/api/acl/role'
import { formatTime } from '@/util/time.ts'

let settingStore = useLayOutSettingStore()
//当前页码
let pageNo = ref<number>(1)
//一页展示几条数据
let pageSize = ref<number>(10)
//搜索角色关键字
let keyword = ref<string>('')
//存储全部已有的角色
let allRole = ref<RoleData[]>([])
//角色总个数
let total = ref<number>(0)
//控制对话框的显示与隐藏
let dialogVisite = ref<boolean>(false)
//获取form组件实例
let form = ref<any>()
//控制抽屉显示与隐藏
let drawer = ref<boolean>(false)
//收集新增角色数据
let RoleParams = reactive<RoleData>({
  name: '',
  code: '',
  description: '',
})
//准备一个数组:数组用于存储勾选的节点的ID(四级的)
let selectArr = ref<number[]>([])
//定义数组存储用户权限的数据
let menuArr = ref<Permission[]>()
//获取tree组件实例
let tree = ref<any>()
//组件挂载完毕
onMounted(() => {
  //获取角色请求
  getHasRole()
})
//获取全部用户信息的方法|分页器当前页码发生变化的回调
const getHasRole = async (pager = 1) => {
  //修改当前页码
  pageNo.value = pager
  let result: RoleResponseData = await reqAllRoleList(
    pageNo.value,
    pageSize.value,
    keyword.value,
  )
  if (result.code == 1) {
    total.value = result.data.total
    allRole.value = result.data.records
  }
}
//下拉菜单的回调
const sizeChange = () => {
  getHasRole()
}
//搜索按钮的回调
const search = () => {
  //再次发请求根据关键字
  getHasRole()
  keyword.value = ''
}
//重置按钮的回调
const reset = () => {
  settingStore.refresh = !settingStore.refresh
}
//添加角色按钮的回调
const addRole = () => {
  //对话框显示出来
  dialogVisite.value = true
  //清空数据
  Object.assign(RoleParams, {
    name: '',
    code: '',
    description: '',
    id: 0,
  })
  //清空上一次表单校验错误结果
  nextTick(() => {
    form.value.clearValidate('name')
  })
}
//更新已有的角色按钮的回调
const updateRole = (row: RoleData) => {
  //显示出对话框
  dialogVisite.value = true
  //存储已有的角色----带有ID的
  Object.assign(RoleParams, row)
  //清空上一次表单校验错误结果
  nextTick(() => {
    form.value.clearValidate('name')
  })
}
//自定义校验规则的回调
const validatorRoleName = (value: any, callBack: any) => {
  if (value.trim().length >= 2) {
    callBack()
  } else {
    callBack(new Error('角色名称至少两位'))
  }
}
//角色校验规则
const rules = {
  name: [{ required: true, trigger: 'blur', validator: validatorRoleName }],
  code: [{ required: true, trigger: 'blur', message: '角色代码必填' }],
  description: [{ required: true, trigger: 'blur', message: '角色描述必填' }],
}

//确定按钮的回调
const save = async () => {
  //表单校验结果,结果通过在发请求、结果没有通过不应该在发生请求
  await form.value.validate()
  //添加角色|更新角色的请求
  console.log(RoleParams)
  let result: any = await reqAddOrUpdateRole(RoleParams)
  if (result.code == 1) {
    //提示文字
    ElMessage({
      type: 'success',
      message: RoleParams.id ? '更新成功' : '添加成功',
    })
    //对话框显示
    dialogVisite.value = false
    //再次获取全部的已有的角色
    await getHasRole(RoleParams.id ? pageNo.value : 1)
  }
}

//分配权限按钮的回调
//已有的角色的数据
const setPermission = async (row: RoleData) => {
  //抽屉显示出来
  drawer.value = true
  //收集当前要分类权限的角色的数据
  Object.assign(RoleParams, row)
  //根据角色获取权限的数据
  let result: MenuResponseData = await reqAllMenuList(RoleParams.id as number)
  if (result.code == 1) {
    menuArr.value = result.data.allPermissions
    selectArr.value = result.data.checkedPermissions.map((p) => p.id) // 只需要 ID 数组
  }
}
//抽屉确定按钮的回调
const handler = async () => {
  //角色的ID
  const roleId = RoleParams.id as number
  //选中节点的ID
  let arr = tree.value ? tree.value.getCheckedKeys() : []
  //半选的ID
  let arr1 = tree.value ? tree.value.getHalfCheckedKeys() : []
  let permissionId = arr.concat(arr1)
  //下发权限
  let result: any = await reqSetPermission(
    roleId,
    permissionId.length ? permissionId : selectArr.value,
  )
  if (result.code == 200) {
    //抽屉关闭
    drawer.value = false
    //提示信息
    ElMessage({ type: 'success', message: '分配权限成功' })
    //页面刷新
    window.location.reload()
  }
}

//删除已有的角色
const removeRole = async (id: number) => {
  let result: any = await reqRemoveRole(id)
  if (result.code == 1) {
    //提示信息
    ElMessage({ type: 'success', message: '删除成功' })
    getHasRole(allRole.value.length > 1 ? pageNo.value : pageNo.value - 1)
  }
}
</script>

<style scoped>
.role-container {
  position: relative;
  padding: 20px;
  min-height: calc(100vh - 100px);
  overflow: hidden;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e8f0 100%);
}

/* 装饰元素 */
.decoration-circle {
  position: absolute;
  border-radius: 50%;
  opacity: 0.5;
  z-index: 0;
}

.decoration-circle-1 {
  width: 300px;
  height: 300px;
  background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
  top: -100px;
  right: -100px;
  filter: blur(60px);
}

.decoration-circle-2 {
  width: 200px;
  height: 200px;
  background: linear-gradient(135deg, #3b82f6 0%, #2dd4bf 100%);
  bottom: -50px;
  left: -50px;
  filter: blur(40px);
}

.decoration-circle-3 {
  width: 150px;
  height: 150px;
  background: linear-gradient(135deg, #f97316 0%, #f43f5e 100%);
  top: 40%;
  left: 60%;
  filter: blur(50px);
}

.search-card,
.table-card {
  position: relative;
  z-index: 1;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
  backdrop-filter: blur(10px);
  background-color: rgba(255, 255, 255, 0.9);
  margin-bottom: 20px;
  overflow: hidden;
}

.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.button-group {
  display: flex;
  justify-content: flex-start;
  margin-bottom: 15px;
  gap: 10px;
}

.role-table {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.role-name-cell,
.time-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
}

.description-cell {
  max-width: 200px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.dialog-footer,
.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 10px;
}

.drawer-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #334155;
}

.permission-container {
  padding: 10px;
}

.current-role-info {
  font-weight: 600;
  color: #334155;
  padding: 6px 10px;
  background-color: rgba(99, 102, 241, 0.08);
  border-radius: 6px;
  display: inline-flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 15px;
}

.permission-checkbox-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
  padding: 5px;
}

.permission-checkbox {
  margin-right: 0;
  margin-bottom: 5px;
  transition: all 0.3s;
  padding: 6px 8px;
  border-radius: 6px;
}

.permission-checkbox:hover {
  background-color: rgba(99, 102, 241, 0.05);
}

.permission-item {
  display: flex;
  align-items: center;
  gap: 6px;
}

.permission-name {
  margin-left: 4px;
  font-weight: 500;
  color: #475569;
}

.permission-desc {
  margin-left: auto;
}

/* 动画效果 */
@keyframes float {
  0%,
  100% {
    transform: translateY(0) scale(1);
  }
  50% {
    transform: translateY(-20px) scale(1.05);
  }
}

.fade-enter-active,
.fade-leave-active {
  transition:
    opacity 0.6s ease,
    transform 0.6s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  transform: translateY(-20px);
}

.slide-fade-enter-active {
  transition: all 0.5s cubic-bezier(0.19, 1, 0.22, 1);
}

.slide-fade-leave-active {
  transition: all 0.5s cubic-bezier(0.19, 1, 0.22, 1);
}

.slide-fade-enter-from,
.slide-fade-leave-to {
  transform: translateY(30px);
  opacity: 0;
}

/* 添加响应式调整 */
@media screen and (max-width: 768px) {
  .role-container {
    padding: 10px;
  }

  .button-group {
    flex-direction: column;
    gap: 10px;
  }

  .pagination {
    flex-wrap: wrap;
  }
}
</style>
